﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMSABL;
using WMSABL.SY;
using WMSAML.SY;
using ElectronicWMSA.Comm.ClassFiles;
using ElectronicWMSA.Comm.Forms.Message;

namespace ElectronicWMSA.SY
{
    public partial class MenuFrm : Form
    {
        #region
        PublicDataSet bll_CommonPub = new PublicDataSet();
        TSystemRegistBLL bll_System = new TSystemRegistBLL();
        public MenuFrm()
        {
            InitializeComponent();
            this.linkLabelClose.BackColor = Color.Transparent;
            this.linkLabelCloseElse.BackColor = Color.Transparent;
            this.linkLabellinkLabelCloseAll.BackColor = Color.Transparent;
            this.DBindSystem_meun();
            this.DBindchkListBoxPermisission();
            this.labFold.BackColor = Color.Transparent;
            this.labExpansion.BackColor = Color.Transparent;
            this.labelShow.BackColor = Color.Transparent;
            DataSet ds = bll_CommonPub.GetDataSet("TUserRoleRelation", " User_id=" + SystemVariable.User_ID + " AND Role_id=4 ");
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    labelForm.Visible = true;
                    txtForm.Visible = true;
                }
            }
        }
        #endregion

        #region 绑定
        public void DBindchkListBoxPermisission()
        {
            DataSet ds = new DataSet();
            ds = bll_CommonPub.GetDataSet("TDictionary_Category", "SortID=1");
            this.chkListBoxPermisission.DataSource = ds.Tables[0];
            this.chkListBoxPermisission.ValueMember = "ID";
            this.chkListBoxPermisission.DisplayMember = "Value";
        }
        public void DBindSystem_meun()
        {
            this.tvMeun.Nodes.Clear();
            DataSet ds = new DataSet();
            ds = bll_System.GetList_SystemMeun();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dv = new DataView(dt);
            dv.RowFilter = "headID=0";
            foreach (DataRowView drv in dv)
            {
                TreeNode node = new TreeNode();
                node.Text = drv["Menu_Name"].ToString();
                node.Name = drv["ID"].ToString();
                tvMeun.Nodes.Add(node);
                this.AddNodes(dt, node);
            }
            this.tvMeun.Nodes[0].Expand();
            this.tvMeun.SelectedNode = tvMeun.TopNode; //最顶端节点选中
        }

        /// <summary>
        /// AddNodes
        /// </summary>
        /// <param name="dt">dt</param>
        /// <param name="node">node</param>
        public void AddNodes(DataTable dt, TreeNode node)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "headID='" + node.Name + "'";
            foreach (DataRowView row in dv)
            {
                TreeNode replyNode = new TreeNode();
                replyNode.Text = row["Menu_Name"].ToString();
                replyNode.Name = row["ID"].ToString();
                node.Nodes.Add(replyNode);
                this.AddNodes(dt, replyNode);
            }
        }
        #endregion

        #region 菜单事件
        private int headID = 0;
        private int _id = 0;
        public bool isPermissions = false;
        private void tvMeun_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.headID = 0;

            #region 清空权限选中
            for (int y = 0; y < chkListBoxPermisission.Items.Count; y++)
            {
                DataRowView dv = (DataRowView)chkListBoxPermisission.Items[y];
                this.chkListBoxPermisission.SetItemChecked(y, false);
            }
            #endregion

            //选中菜单ID
            this._id = Convert.ToInt32(e.Node.Name);
            if (e.Node != null)
            {
                TSystemMenuEntity entity1 = new TSystemMenuEntity();
                entity1 = bll_System.GetEntity_SystemMenu(_id);
                if (entity1 == null) return;

                //获取父级
                TSystemMenuEntity entity2 = new TSystemMenuEntity();
                entity2 = bll_System.GetEntity_SystemMenu(entity1.HeadID);

                this.headID = entity1.ID;
                this.txtMenuName.Text = entity1.Menu_Name;
                this.txtForm.Text = entity1.Url1;
                this.txtMark.Text = entity1.Mark;

                if (headID == 1)
                {
                    this.txtHeadIDName.Text = "根目录";
                }
                else
                {
                    this.txtHeadIDName.Text = entity2.Menu_Name;
                }
                if (e.Node.LastNode != null)
                {
                    this.txtMenuName.Enabled = true;
                    this.chkListBoxPermisission.Enabled = false;
                    this.txtForm.Enabled = false;
                    this.txtNameSpac.Enabled = false;
                }
                else
                {
                    isPermissions = true;
                    this.txtMenuName.Enabled = true;
                    this.chkListBoxPermisission.Enabled = true;
                    this.txtForm.Enabled = true;
                    this.txtNameSpac.Enabled = true;
                }
                DataSet ds = new DataSet();
                ds = bll_CommonPub.GetDataSet("TPermissions", "MoudleID=" + entity1.ID + " AND Display=1");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string str = "";
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        str += ds.Tables[0].Rows[i]["Type"].ToString() + ",";
                    }
                    string[] s_meuns = str.Split(',');
                    for (int i = 0; i < s_meuns.Length - 1; i++)
                    {
                        for (int y = 0; y < chkListBoxPermisission.Items.Count; y++)
                        {
                            DataRowView dv = (DataRowView)chkListBoxPermisission.Items[y];
                            if (dv.DataView[y].Row["ID"].ToString() == s_meuns[i])
                            {
                                this.chkListBoxPermisission.SetItemChecked(y, true);
                            }
                        }
                    }
                }
                else
                {
                    for (int y = 0; y < chkListBoxPermisission.Items.Count; y++)
                    {
                        DataRowView dv = (DataRowView)chkListBoxPermisission.Items[y];
                        this.chkListBoxPermisission.SetItemChecked(y, false);
                    }
                }
            }
            this.labShow.Text = "信息提示！";
        }
        #endregion

        #region 新增
        private void btnNewMenu_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("新增")) return;
            if (_id > 0)
            {
                TSystemMenuEntity entity1 = new TSystemMenuEntity();
                entity1 = bll_System.GetEntity_SystemMenu(Convert.ToInt32(_id));
                if (entity1 == null) return;
                TSystemMenuEntity entity2 = new TSystemMenuEntity();
                entity2 = bll_System.GetEntity_SystemMenu(entity1.HeadID);
                this.headID = entity1.ID;
                this.txtHeadIDName.Text = entity1.Menu_Name;
                this.txtMenuName.Text = "";
                this.txtForm.Text = "";
                this.txtMark.Text = "";
                this.txtMenuName.Enabled = true;
                this.txtForm.Enabled = true;
                this.txtMark.Enabled = true;
                this.chkListBoxPermisission.Enabled = true;
            }
            else
            {
                MessageClass.error("请选择目录......");
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("新增")) return;

            TSystemMenuEntity entity = new TSystemMenuEntity();
            TSystemMenuEntity entity2 = new TSystemMenuEntity();
            entity.HeadID = headID;
            entity.IsShow = "1";
            entity.Menu_Name = this.txtMenuName.Text.Trim();
            entity.Url1 = this.txtForm.Text.Trim();
            entity.Image = "/..";
            entity.Mark = this.txtMark.Text.Trim();
            if (!DBValidate())
                return;
            if (MessageClass.enquire("确认添加信息！") == DialogResult.OK)
            {
                entity2 = bll_System.Add_SystemMenu(entity);
                if (entity2 != null)
                {
                    SetMoudlePermisissionsAdd(entity2.ID);
                    if (MessageClass.enquire("是否继续添加信息！") == DialogResult.OK)
                    {
                    }
                    else
                    {
                        this.DBindSystem_meun();
                        this.DBClear();
                    }
                }
                else
                {
                   MessageClass.error("失败！");
                }
            }
        }

        #endregion

        #region 修改
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("编辑"))
                return;
            TSystemMenuEntity entity = new TSystemMenuEntity();
            entity = bll_System.GetEntity_SystemMenu(headID);
            entity.HeadID = headID;
            entity.Menu_Name = txtMenuName.Text.Trim();
            entity.Url1 = txtForm.Text.Trim();
            entity.Mark = txtMark.Text.Trim();
            #region 验证
            if (headID == 0)
            {
                MessageClass.error("请指定所属父级！");
                return;
            }
            if (headID == 1)
            {
                if (MessageClass.enquire("确认修改信息！") == DialogResult.OK)
                {
                    if (bll_System.Update_SystemMenu(entity))
                    {
                        SetMoudlePermisissionsUpdate(entity.ID);
                        this.labShow.Text = "成功！";
                    }
                    else
                    {
                        this.labShow.Text = "失败！";
                    }
                    this.DBClear();
                }
                return;
            }
            if (txtMenuName.Text.Trim() == "")
            {
                MessageClass.error("请填写菜单名称！");
                this.txtMenuName.Focus();
                return;
            }
            DataSet ds = bll_CommonPub.GetDataSet("TSystemMenu", " Menu_Name='" + txtMenuName.Text.Trim() + "' AND  HeadID=" + entity.HeadID + "  AND ID!='" + headID + "'");
            int count = 0;
            if (ds.Tables[0].Rows.Count > 0)
            {
                count = ds.Tables[0].Rows.Count;
            }
            if (count > 0)
            {
                this.labShow.Text = "菜单名称不能重复！";
                this.txtMenuName.Focus();
                return;
            }
            #endregion
            if (MessageClass.enquire("确认修改信息！") == DialogResult.OK)
            {
                if (bll_System.Update_SystemMenu(entity))
                {
                    SetMoudlePermisissionsUpdate(entity.ID);
                    this.labShow.Text = "成功！";
                }
                else
                {
                    this.labShow.Text = "失败！";
                }
                this.DBClear();
            }
        }
        /// 验证 
        public bool DBValidate()
        {
            bool falg = false;
            if (headID == 0)
            {
                MessageClass.error("请指定所属父级！");
                return falg;
            }
            if (txtMenuName.Text.Trim() == "")
            {
                MessageClass.error("请填写菜单名称！");
                this.txtMenuName.Focus();
                return falg;
            }
            DataSet ds = bll_CommonPub.GetDataSet("TSystemMenu", " Menu_Name='" + txtMenuName.Text.Trim() + "'");
            int count = 0;
            if (ds.Tables[0].Rows.Count > 0)
            {
                count = ds.Tables[0].Rows.Count;
            }
            if (count > 0)
            {
                this.labShow.Text = "菜单名称不能重复！";
                this.txtMenuName.Focus();
                return falg;
            }
            return falg = true;
        }

        #region 重置
        public void DBClear()
        {
            this.txtHeadIDName.Text = "";
            this.txtMenuName.Text = "";
            this.txtForm.Text = "";
            this.txtMark.Text = "";
            this.headID = 0;
            this.DBindSystem_meun();
            this.DBindchkListBoxPermisission();
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.DBClear();
        }
        #endregion

        #endregion

        #region 删除
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("删除")) return;
            if (headID == 0)
            {
                this.labShow.Text = "请选择信息！";
                return;
            }
            TSystemMenuEntity entity = new TSystemMenuEntity();
            entity = bll_System.GetEntity_SystemMenu(headID);
            entity.IsShow = "2";
            if (MessageClass.enquire("删除信息！") == DialogResult.OK)
            {
                if (bll_System.Update_SystemMenu(entity))
                    this.labShow.Text = "删除成功！刷新需重新登录系统";
                else
                {
                    this.labShow.Text = "删除失败！";
                    return;
                }
                DBClear();
            }
        }
        #endregion

        #region 配置权限
        TPermissions_BLL bll_TPermissions = new TPermissions_BLL();
        private void SetMoudlePermisissionsAdd(int m_id)
        {
            string[] pid = str.Split(',');
            DataSet ds = new DataSet();
            ds = bll_CommonPub.GetDataSet("TDictionary_Category", "SortID=1");
            TPermissions_Entity entity = new TPermissions_Entity();
            if (m_id > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"].ToString());
                    entity.MoudleID = m_id;
                    entity.Type = id;
                    if (pid != null && pid.Contains(id.ToString()))
                    {
                        entity.Display = 1;
                    }
                    else
                    {
                        entity.Display = 0;
                    }
                    bll_TPermissions.Add(entity);
                }
            }
            str = "";
        }
        private void SetMoudlePermisissionsUpdate(int m_id)
        {
            DataSet ds1 = new DataSet();
            ds1 = bll_CommonPub.GetDataSet("TPermissions", "MoudleID=" + m_id + "");
            if (ds1.Tables[0].Rows.Count == 0)
            {
                SetMoudlePermisissionsAdd(m_id);
            }
            else
            {
                string[] pid = str.Split(',');
                DataSet ds = new DataSet();
                ds = bll_CommonPub.GetDataSet("TDictionary_Category", "SortID=1");
                TPermissions_Entity entity = new TPermissions_Entity();
                if (m_id > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        TPermissions_Entity entity1 = new TPermissions_Entity();
                        entity1 = bll_TPermissions.GetEntityByMidType(m_id, Convert.ToInt32(ds1.Tables[0].Rows[i]["Type"].ToString()));
                        if (entity1 != null)
                        {
                            entity.ID = entity1.ID;
                            entity.MoudleID = entity1.MoudleID;
                            entity.Type = entity1.Type;
                            int id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"].ToString());
                            if (pid != null && pid.Contains(id.ToString()))
                            {
                                entity.Display = 1;
                            }
                            else
                            {
                                entity.Display = 0;
                            }
                            bll_TPermissions.Update(entity);
                        }
                    }
                }
            }
            str = "";
        }
        #endregion

        #region 排序
        /// <summary>
        /// 向上
        /// </summary>
        private void btnUp_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("移动")) return;

            TreeNode Node = tvMeun.SelectedNode;
            TreeNode PrevNode = Node.PrevNode;//同级树节点 
            if (PrevNode != null)
            {
                TreeNode NewNode = (TreeNode)Node.Clone();//复制此节点为根的所有节点
                if (Node.Parent == null)
                {
                    tvMeun.Nodes.Insert(PrevNode.Index, NewNode);
                }
                else
                {
                    Node.Parent.Nodes.Insert(PrevNode.Index, NewNode);
                    bll_System.Update_SystemMenuFamilyUp(_id);
                    bll_System.Update_SystemMenuFamilyDown(Convert.ToInt32(Node.PrevNode.Name));
                }
                Node.Remove();
                tvMeun.SelectedNode = NewNode;
                tvMeun.SelectedNode.BackColor = Color.Red;
            }
            else
            {
                MessageClass.error("不能再进行排序，请核查！");
                return;
            }
        }

        /// <summary>
        /// 向下
        /// </summary>
        private void btnDown_Click(object sender, EventArgs e)
        {
            if (!SystemVariable.VaildationPermission("移动"))
                return;

            TreeNode Node = tvMeun.SelectedNode;
            TreeNode NextNode = Node.NextNode;
            if (NextNode != null)
            {
                TreeNode NewNode = (TreeNode)Node.Clone();
                if (Node.Parent == null)
                {
                    tvMeun.Nodes.Insert(NextNode.Index + 1, NewNode);
                }
                else
                {
                    Node.Parent.Nodes.Insert(NextNode.Index + 1, NewNode);
                    bll_System.Update_SystemMenuFamilyUp(Convert.ToInt32(Node.NextNode.Name));
                    bll_System.Update_SystemMenuFamilyDown(_id);
                }
                Node.Remove();
                tvMeun.SelectedNode = NewNode;
                tvMeun.SelectedNode.BackColor = Color.Red;
            }
            else
            {
                MessageClass.error("不能再进行排序，请核查！");
                return;
            }
        }

        private void labExpansion_Click(object sender, EventArgs e)
        {
            tvMeun.ExpandAll();
        }
        private void labFold_Click(object sender, EventArgs e)
        {
            tvMeun.CollapseAll();
        }
        #endregion

        #region 获取模块分配权限
        private string str = "";
        private void chkListBoxPermisission_SelectedIndexChanged(object sender, EventArgs e)
        {
            str = "";
            for (int i = 0; i < chkListBoxPermisission.Items.Count; i++)
            {
                if (chkListBoxPermisission.GetItemChecked(i))
                {
                    DataRowView dv = (DataRowView)chkListBoxPermisission.Items[i];
                    str += dv.DataView[i].Row["ID"].ToString() + ",";
                }
            }
        }
        #endregion

        #region 退出
        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }

        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }

        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }
        #endregion

        private void panelRight_Paint(object sender, PaintEventArgs e)
        {

        }
        private void labelShow_DoubleClick(object sender, EventArgs e)
        {
            CMDSQLFrm frm = new CMDSQLFrm();
            frm.ShowDialog();
        }
    }
}
